package cn.zaink;

import lombok.extern.slf4j.Slf4j;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.StandardCharsets;

/**
 * 简单读
 * @author zenghy
 **/
@Slf4j
public class SimpleReadTest extends AbstractZkClient {

    @Override
    public SampleResult runTest(JavaSamplerContext context) {
        String counter = context.getParameter(Arg.COUNTER);
        String prefix = context.getParameter(Arg.NODE_PREFIX);
        int wCounter = context.getIntParameter(Arg.R_COUNTER);
        log.warn("ZK第{}读", wCounter);
        SampleResult result = new SampleResult();
        result.setSampleLabel("ZK节点读测试");
        try {
            // 开始样品事物
            result.sampleStart();
            result.setTimeStamp(System.currentTimeMillis());
            String path = prefix.concat("/node") + counter;

            Stat stat = client.checkExists().forPath(path);
            if (null != stat) {
                byte[] bytes = client.getData().forPath(path);
                result.setResponseData(bytes);
            }
            result.setSuccessful(true);
        } catch (Exception e) {
            log.error("创建zk节点出错：".concat(e.getMessage()));
            result.setSuccessful(false);
            result.setResponseData(e.getMessage(), StandardCharsets.UTF_8.name());
        } finally {
            result.sampleEnd();
            result.setEndTime(System.currentTimeMillis());
            result.setDataType(SampleResult.TEXT);
            latch.countDown();
        }
        return result;
    }
}
